'use strict';

const BaseController = require('./BaseController');
class RoomDetailController extends BaseController {
  async index(){
    let room_id = this.ctx.query.room_id;
    if(id){
      const result = await this.ctx.model.RoomDetail.findAll({where:{room_id}})
      if(result){
        this.ctx.body = {code:1,data:result,msg:""};
      }else{
        this.ctx.body = {code:1,msg:"此房间不存在"};
      }
    }else{
      this.ctx.body = {code:0,msg:"参数不正确"};
    }
    
  }
  async create() {
    const { ctx, app } = this;
    let room = ctx.request.body;
    if(room.id){
        try{
          const c = await ctx.model.RoomDetail.count({where: {user_id: room.user_id}})
          if(c<1){
            let roomCount = await ctx.model.RoomDetail.count({where: {room_id: room.id}})
            if(roomCount>=room.game_num){
              ctx.body = {code:0,msg:'该房间已经满人了'};
              return;
            }
            let roomDeatil = {};
            roomDeatil.room_name = room.name;
            roomDeatil.room_id = room.id;
            roomDeatil.user_id = room.user_id;
            roomDeatil.user_name = room.user_name;
            roomDeatil.room_num = room.num;
            try{
              await ctx.model.RoomDetail.create(roomDeatil)
            }catch(e){
              this.consoleError(e,room)
              ctx.body = {code:0,msg:'该房间号不存在'}
              return;
            }
            roomCount++;
            await ctx.model.Room.update({ person_num:roomCount }, {where: {id: room.id}});
            ctx.body = {code:1,msg:''}
          }else{
            ctx.body = {code:0,msg:'请勿重复加入此房间'}   
          }
        }catch(e){
          this.consoleError(e,room)
          ctx.body = {code:0,msg:'程序错误,请稍后再试'}
        }
    }else{
      ctx.body = {code:0,msg:'参数不正确'}
    }
    
  }
  async update(){
    const { ctx, app } = this;
  }
  async destroy(){
    const { ctx, app } = this;
    let roomDeatilID = ctx.params.id;
    let roomMsg = ctx.request.body;
    try{
      await ctx.service.roomDetail.del({roomDeatilID,roomMsg,ctx});
    }catch(e){
      this.consoleError(e,roomMsg);
      ctx.body = {code:0,msg:'程序错误'}
    }
  }
}

module.exports = RoomDetailController;
